<template>
  <div style="padding: 20px">
    <el-card class="box-card">
      <el-form
        ref="formValidate"
        :model="formValidate"
        :rules="ruleValidate"
        label-width="130px"
      >
        <el-row :gutter="60">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="store_name">
              <el-input
                v-model="formValidate.store_name"
                placeholder="请输入商品名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="cate_id">
              <el-cascader
                style="width: 100%"
                v-model="cateIds"
                :options="optionsMetaShow"
                :show-all-levels="false"
                :props="propA"
                @change="handleCateChange"
              ></el-cascader>
              <!-- <el-select
                style="width: 100%"
                v-model="formValidate.cate_id"
                clearable
                placeholder="请选择商品分类"
                class="filter-item"
                filterable
                :filter-method="dataFilter"
              >
                <el-option
                  v-for="item in optionsMetaShow"
                  :disabled="item.disabled === 0"
                  :value="item.value"
                  :key="item.id"
                  :label="item.label"
                ></el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="60">
          <el-col :span="12">
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="formValidate.price" placeholder="请输入商品价格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input v-model="formValidate.stock" placeholder="请输入库存" />
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row :gutter="60">
          <el-col :span="12">
            <el-form-item label="标签" prop="keyword">
              <el-input
                v-model="formValidate.keyword"
                placeholder="请输入标签,多个用空格隔开"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit_name">
              <el-input
                v-model="formValidate.unit_name"
                placeholder="请输入单位"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="60">
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number
                style="width: 100%"
                v-model="formValidate.sort"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="is_show">
              <el-radio-group v-model="formValidate.is_show">
                <el-radio
                  v-for="dict in dict.type.goods_status"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="是否推荐" prop="is_hot">
              <el-radio-group v-model="formValidate.is_hot">
                <el-radio v-for="dict in dict.type.hot_status" :key="dict.value" :label="dict.value">{{ dict.label
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-form-item label="商品主图" prop="image">
          <Image-upload
            :limit="1"
            v-model="formValidate.image"
            tipText="图片宽高338*342"
          />
        </el-form-item>
        <el-form-item label="轮播图" prop="slider_image">
          <Image-upload
            :limit="9"
            v-model="formValidate.slider_image"
            tipText="图片宽高750*500"
          />
        </el-form-item>
        <!-- <el-form-item label="商品规格" prop="specType">
          <el-radio-group
            v-model="formValidate.spec_type"
            @input="oNselectAttrs()"
          >
            <el-radio
              v-for="dict in dict.type.rule_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item> -->
        <el-form-item v-show="formValidate.spec_type === '0'">
          <el-table :data="oneFormValidate" style="width: 100%">
            <el-table-column label="图片" align="center" prop="pic" width="200">
              <template slot-scope="scope">
                <Image-uploada :limit="1" v-model="scope.row.pic" />
              </template>
            </el-table-column>
            <el-table-column prop="price" label="售价" align="center">
              <template slot-scope="scope">
                <el-input :min="0" type="number" v-model="scope.row.price" />
              </template>
            </el-table-column>
            <el-table-column prop="cost" label="成本价" align="center">
              <template slot-scope="scope">
                <el-input :min="0" type="number" v-model="scope.row.cost" />
              </template>
            </el-table-column>
            <el-table-column prop="ot_price" label="原价" align="center">
              <template slot-scope="scope">
                <el-input :min="0" type="number" v-model="scope.row.ot_price" />
              </template>
            </el-table-column>

            <el-table-column prop="stock" label="库存" align="center">
              <template slot-scope="scope">
                <el-input
                  :min="0"
                  type="number"
                  v-model="scope.row.stock"
                  maxlength="7"
                />
              </template>
            </el-table-column>
            <!-- <el-table-column prop="bar_code" label="商品编号" align="center">
              <template slot-scope="scope">
                <el-input type="text" v-model="scope.row.bar_code" />
              </template>
            </el-table-column> -->
          </el-table>
        </el-form-item>
        <el-form-item
          v-show="formValidate.spec_type === '1'"
          label="选择规格"
          prop="cateId"
        >
          <el-row :gutter="10">
            <el-col :span="8">
              <el-select
                v-model="selectAttrs"
                placeholder="请选择规格"
                clearable
                style="width: 100%"
                @change="setAttrs"
              >
                <el-option
                  v-for="dict in specificationsList"
                  :key="dict.id"
                  :label="dict.ruleName"
                  :value="dict.ruleValue"
                />
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item v-if="attrs.length !== 0">
          <div v-for="(item, index) in attrs" :key="index">
            <div class="acea-row row-middle">
              <span class="mr5">{{ item.value }}</span>
              <i
                class="el-icon-circle-close"
                @click="handleRemoveRole(index)"
              ></i>
            </div>
            <div class="rulesBox">
              <el-tag
                type="dot"
                closable
                color="primary"
                v-for="(j, indexn) in item.detail"
                :key="indexn"
                :name="j"
                class="mr20"
                @close="handleRemove2(item.detail, indexn)"
                >{{ j }}</el-tag
              >
              <el-input
                placeholder="请输入属性名称"
                v-model="item.detail.attrsVal"
                style="width: 200px"
              >
                <el-button
                  slot="append"
                  type="primary"
                  @click="createAttr(item.detail.attrsVal, index)"
                  >添加</el-button
                >
              </el-input>
            </div>
          </div>
        </el-form-item>
        <el-form-item v-if="createBnt">
          <el-button type="primary" icon="md-add" @click="addBtn" class="mr15"
            >添加新规格</el-button
          >
          <el-button type="success" @click="generate">立即生成</el-button>
        </el-form-item>
        <el-row v-if="showIput">
          <el-col :xl="6" :lg="9" :md="10" :sm="24" :xs="24">
            <el-form-item label="规格：">
              <el-input
                placeholder="请输入规格"
                v-model="formDynamic.attrsName"
              />
            </el-form-item>
          </el-col>
          <el-col :xl="6" :lg="9" :md="10" :sm="24" :xs="24">
            <el-form-item label="规格值：">
              <el-input
                v-model="formDynamic.attrsVal"
                placeholder="请输入规格值"
              />
            </el-form-item>
          </el-col>
          <el-col :xl="6" :lg="5" :md="10" :sm="24" :xs="24">
            <el-button type="primary" @click="createAttrName">确定</el-button>
            <el-button type="danger" @click="offAttrName">取消</el-button>
          </el-col>
        </el-row>
        <el-form-item
          label="商品属性"
          v-if="
            manyFormValidate.length &&
            formValidate.header.length !== 0 &&
            attrs.length !== 0
          "
        >
          <el-table :data="manyFormValidate" size="small" style="width: 90%">
            <el-table-column
              type="myindex"
              v-for="(item, index) in formValidate.header"
              :key="index"
              :label="item.title"
              :property="item.slot"
              align="center"
            >
              <template slot-scope="scope">
                <div v-if="scope.column.property == 'pic'" align="center">
                  <Image-uploada
                    :limit="1"
                    v-model="scope.row[scope.column.property]"
                  />
                </div>
                <div
                  v-else-if="scope.column.property.indexOf('value') != -1"
                  align="center"
                >
                  {{ scope.row[scope.column.property] }}
                </div>
                <div
                  v-else-if="scope.column.property == 'action'"
                  align="center"
                >
                  <a @click="delAttrTable(scope.$index)" align="center">删除</a>
                </div>
                <div v-else align="center">
                  <el-input
                    :min="0"
                    type="number"
                    v-model="scope.row[scope.column.property]"
                    align="center"
                    @input="inputChangeMore(scope)"
                  />
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="运费模板：" prop="temp_id">
          <div class="acea-row">
            <el-select v-model="formValidate.temp_id" class="mr20">
              <el-option
                v-for="(item, index) in templateList"
                :value="item.id"
                :key="index"
                :label="item.name"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <!-- <el-form-item label="商品简介" prop="storeInfo">
          <el-input type="textarea" v-model="formValidate.storeInfo" placeholder="请输入商品简介" />
        </el-form-item> -->
        <el-form-item label="商品详情" prop="description">
          <editor v-model="formValidate.description" :min-height="192" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit('formValidate')"
            >保存</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import {
  fromatAttrApi,
  addStoreProduct,
  getStoreProduct,
} from "@/api/business/storeProduct";
import { listShowStoreProductCategory } from "@/api/business/storeProduct";
import { listStoreProductRule } from "@/api/business/storeProductRule";
import { listParentCategory } from "@/api/business/storeCategory";
export default {
  name: "Add",
  dicts: ["goods_status", "hot_status", "rule_status"],
  data() {
    return {
      cateIds: [],
      propA: {
        label: "cateName",
        value: "id",
      },
      templateList: [],
      optionsMetaShow: [],
      formDynamic: {
        attrsName: "",
        attrsVal: "",
      },
      formDynamicNameData: [],
      storeCategoryList: [],
      specificationsList: [],
      manyFormValidate: [],
      isBtn: false,
      attrs: [],
      createBnt: false,
      showIput: false,
      //规格选择
      selectAttrs: "",
      formValidate: {
        giveIntegralType: "0",
        imageArr: [],
        sliderImageArr: [],
        store_name: "",
        cate_id: "",
        keyword: "",
        unit_name: "",
        store_info: "",
        image: "",
        slider_image: [],
        description: "",
        ficti: 0,
        give_integral: 0,
        sort: 0,
        is_show: "1",
        is_hot: "0",
        is_benefit: 0,
        is_best: 0,
        is_new: 0,
        is_good: 0,
        is_postage: 0,
        is_sub: "1",
        is_integral: 0,
        id: 0,
        spec_type: "0",
        temp_id: "",
        attrs: [],
        items: [
          {
            pic: "",
            price: 0,
            cost: 0,
            ot_price: 0,
            stock: 0,
            bar_code: "",
            integral: 0,
            handsel: 0,
          },
        ],
        header: [],
        selectRule: "",
        isPresell: 0,
      },
      oneFormValidate: [
        {
          imageArr: [],
          pic: "",
          price: 2,
          cost: 0,
          ot_price: 0,
          stock: 0,
          seckill_stock: 0,
          seckill_price: 0,
          pink_stock: 0,
          pink_price: 0,
          bar_code: "",
          weight: 0,
          volume: 0,
          brokerage: 0,
          brokerage_two: 0,
          integral: 0,
          handsel: 2,
          isPresell: 0,
        },
      ],
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      //图片根路径
      imageURL: process.env.VUE_APP_BASE_API,
      ruleValidate: {
        store_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        cate_id: [
          { required: true, message: "请选择商品分类", trigger: "change" },
        ],
        keyword: [
          { required: true, message: "请输入商品关键字", trigger: "blur" },
        ],
        unit_name: [
          { required: true, message: "请输入单位", trigger: "blur" },
          {
            pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/,
            message: "单位不能是数字",
            trigger: "blur",
          },
        ],
        store_info: [
          { required: false, message: "请输入商品简介", trigger: "blur" },
        ],
        spec_type: [
          { required: true, message: "请选择商品规格", trigger: "change" },
        ],
        selectRule: [
          { required: true, message: "请选择商品规格属性", trigger: "change" },
        ],
        temp_id: [
          {
            required: true,
            message: "请选择运费模板",
            trigger: "change",
            type: "number",
          },
        ],
      },
    };
  },
  watch: {
    "formValidate.image": function (val) {
      if (val) {
        this.oneFormValidate[0].pic = val;
      }
    },
  },
  created() {
    this.getList();
    // this.getCategory();
    // this.getspecifications();
    // if (this.$route.params.id) {
    //   this.getInfo();
    // }
  },
  methods: {
    handleCateChange(val) {
      this.formValidate.cate_id = val[1];
    },
    getList() {
      listParentCategory().then((response) => {
        this.optionsMetaShow = this.handleTree(response.data, "id", "pid");
        console.log(this.optionsMetaShow);
        this.getInfo();
      });
    },
    // 详情
    getInfo() {
      let that = this;
      let id = that.$route.params.id || 0;
      getStoreProduct(id).then(async (res) => {
        let data = res.data.productInfo;

        if (data) {
          let cate_id = parseInt(data.cate_id) || 0;
          this.optionsMetaShow.forEach((item) => {
            if (item.children && item.children.length > 0) {
              item.children.forEach((row) => {
                if (row.id === cate_id) {
                  this.cateIds = [item.id, row.id];
                }
              });
            }
          });
          console.log(1, this.cateIds);
          this.attrs = data.items || [];
          that.formValidate = data;
          that.formValidate.cate_id = cate_id;
          that.oneFormValidate = [data.attr];
          that.formValidate.header = [];
          that.generate();
          that.manyFormValidate = data.attrs;
          if (data.spec_type === "0") {
            that.manyFormValidate = [];
          } else {
            that.createBnt = true;
            that.oneFormValidate = [
              {
                pic: "",
                price: 0,
                cost: 0,
                ot_price: 0,
                stock: 0,
                seckill_stock: 0,
                seckill_price: 0,
                pink_stock: 0,
                pink_price: 0,
                bar_code: "",
                weight: 0,
                volume: 0,
                brokerage: 0,
                brokerage_two: 0,
                integral: 0,
                handsel: 0,
              },
            ];
          }
        }
        // that.optionsMetaShow = res.data.cateList;
        that.specificationsList = res.data.ruleList;
        that.templateList = res.data.tempList;
      });
    },
    // 删除表格中的属性
    delAttrTable(index) {
      this.manyFormValidate.splice(index, 1);
    },
    //获取分类列表
    getCategory() {
      listShowStoreProductCategory().then((response) => {
        // this.storeCategoryList = response.data.cateList;
        // this.optionsMetaShow = this.storeCategoryList;
      });
    },
    //获取规格列表
    getspecifications() {
      listStoreProductRule({ pageNum: 1, pageSize: 99 }).then((response) => {
        this.specificationsList = response.rows;
      });
    },
    dataFilter(val) {
      this.value = val;
      if (val) {
        this.optionsMetaShow = this.treeSelect.filter((item) => {
          if (
            !!~item.label.indexOf(val) ||
            !!~item.label.toUpperCase().indexOf(val.toUpperCase())
          ) {
            return true;
          }
        });
      } else {
        this.optionsMetaShow = this.treeSelect;
      }
    },
    OnGenerate() {
      let arr = [];
      this.formValidate.items[0].detail.forEach((val) => {
        this.formValidate.items[1].detail.forEach((data) => {
          let obj = {};
          this.formValidate.items.forEach((element, inx) => {
            console.log(val, data, inx);
            if (inx == 0) {
              obj[`${element.value}`] = val;
            }
            if (inx == 1) {
              obj[`${element.value}`] = data;
            }
          });
          let Att = {
            imageArr: [],
            detail: {},
            pic: "",
            price: "",
            cost: "",
            ot_price: "",
            stock: null,
            seckill_stock: 0,
            seckill_price: 0,
            pink_stock: 0,
            pink_price: 0,
            bar_code: "",
            weight: "",
            volume: null,
            brokerage: 0,
            brokerage_two: 0,
            integral: "",
            handsel: "",
            isPresell: 0,
          };
          Att.detail = obj;
          arr.push(Att);
        });
      });
      this.formValidate.attrs = arr;
    },
    // 重置选择
    oNselectAttrs() {
      // this.formValidate.attrs = [];
      // let attr = {
      //   imageArr: [],
      //   detail: {},
      //   pic: "",
      //   price: "",
      //   cost: "",
      //   ot_price: "",
      //   stock: null,
      //   seckill_stock: 0,
      //   seckill_price: 0,
      //   pink_stock: 0,
      //   pink_price: 0,
      //   bar_code: "",
      //   weight: "",
      //   volume: null,
      //   brokerage: 0,
      //   brokerage_two: 0,
      //   integral: "",
      //   handsel: "",
      //   isPresell: 0,
      // };
      // this.formValidate.attrs.push(attr);
    },
    //选择规格数据展示
    setAttrs(e) {
      console.log(e);
      this.attrs = e;
      this.createBnt = true;
      // console.log(this.getCombination(e));
    },
    getCombination(array) {
      let resultArry = [];
      array.forEach((arrItem) => {
        if (resultArry.length === 0) {
          resultArry = arrItem.detail;
        } else {
          const emptyArray = [];
          resultArry.forEach((item) => {
            arrItem.detail.forEach((value) => {
              if (Array.isArray(item)) {
                emptyArray.push([...item, value]);
              } else {
                emptyArray.push([item, value]);
              }
            });
          });
          resultArry = emptyArray;
        }
      });
      return resultArry;
    },
    // 添加按钮
    addBtn() {
      this.clearAttr();
      this.createBnt = false;
      this.showIput = true;
    },
    // 立即生成
    generate() {
      fromatAttrApi(this.formValidate.id, {
        attrs: this.attrs,
        isPresell: this.formValidate.isPresell,
      }).then((res) => {
        console.info("立即生成", res);
        this.manyFormValidate = res.value;
        this.formValidate.header = res.header;
        console.log(this.$route.params.id, this.formValidate.spec_type);
        if (this.formValidate.spec_type === "1") {
          this.manyFormValidate.map((item) => {
            item.pic = this.formValidate.image;
          });
          console.log(111, this.manyFormValidate);
          // this.oneFormBatch[0].pic = this.formValidate.image;
        }
      });
    },
    // 取消
    offAttrName() {
      this.showIput = false;
      this.createBnt = true;
    },
    clearAttr() {
      this.formDynamic.attrsName = "";
      this.formDynamic.attrsVal = "";
    },
    // 删除规格
    handleRemoveRole(index) {
      this.attrs.splice(index, 1);
      // this.manyFormValidate.splice(index, 1);
    },
    // 删除属性
    handleRemove2(item, index) {
      item.splice(index, 1);
    },
    // 添加规则名称
    createAttrName() {
      if (this.formDynamic.attrsName && this.formDynamic.attrsVal) {
        let data = {
          value: this.formDynamic.attrsName,
          detail: [this.formDynamic.attrsVal],
        };
        this.attrs.push(data);
        var hash = {};
        this.attrs = this.attrs.reduce(function (item, next) {
          hash[next.value] ? "" : (hash[next.value] = true && item.push(next));
          return item;
        }, []);
        this.clearAttr();
        this.showIput = false;
        this.createBnt = true;
      } else {
        this.$message.warning("请添加完整的规格！");
      }
    },
    // 添加属性
    createAttr(num, idx) {
      if (num) {
        this.attrs[idx].detail.push(num);
        var hash = {};
        this.attrs[idx].detail = this.attrs[idx].detail.reduce(function (
          item,
          next
        ) {
          hash[next] ? "" : (hash[next] = true && item.push(next));
          return item;
        },
        []);
      } else {
        this.$message.warning("请添加属性！");
      }
    },
    inputChange(scope) {
      this.oneFormValidate[scope.$index].handsel = scope.row.price;
    },
    inputChangeMore(scope) {
      if (scope.column.property === "price") {
        this.manyFormValidate[scope.$index].handsel = scope.row.price;
      }
    },
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.formValidate.spec_type === "0") {
            this.formValidate.attrs = this.oneFormValidate;
            console.log(this.formValidate.spec_type, this.oneFormValidate);
            this.formValidate.header = [];
            this.formValidate.items = [];
          } else {
            this.formValidate.items = this.attrs;
            this.formValidate.attrs = this.manyFormValidate;
          }
          if (
            this.formValidate.spec_type === "1" &&
            this.manyFormValidate.length === 0
          ) {
            return this.$message.warning("请点击生成规格！");
          }
          console.info("formValidate------", this.formValidate.unit_name);
          if (this.formValidate.isPresell == 0) {
            this.formValidate.balanceTime = null;
          }
          let flag = true;
          for (let i = 0; i < this.formValidate.attrs.length; i++) {
            if (this.formValidate.attrs[i].price == 0) {
              flag = false;
            }
          }
          if (!flag) {
            this.$message.warning("售价需要大于0");
            return;
          }
          var is_integral = this.formValidate.is_integral;
          if (is_integral == 1) {
            for (let i = 0; i < this.formValidate.attrs.length; i++) {
              if (this.formValidate.attrs[i].integral == 0) {
                flag = false;
              }
            }
            if (!flag) {
              this.$message.warning("兑换积分需要大于0");
              return;
            }
          }

          for (let i = 0; i < this.formValidate.attrs.length; i++) {
            if (this.formValidate.attrs[i].ot_price == 0) {
              flag = false;
            }
          }
          if (!flag) {
            this.$message.warning("原价需要大于0");
            return;
          }
          if (this.formValidate.isPresell == 1) {
            for (let i = 0; i < this.formValidate.attrs.length; i++) {
              if (
                this.formValidate.attrs[i].handsel == 0 ||
                this.formValidate.attrs[i].handsel >
                  this.formValidate.attrs[i].price
              ) {
                flag = false;
              }
            }
            if (!flag) {
              this.$message.warning("定金需要大于0，且小于等于售价");
              return;
            }
          }
          addStoreProduct(this.formValidate)
            .then(async (res) => {
              this.$message({
                message: "操作成功",
                type: "success",
              });
              setTimeout(() => {
                this.$router.push({ path: "/goods/storeProduct" });
              }, 500);
            })
            .catch((res) => {
              // this.$message({
              //   message:res.message,
              //   type: 'error'
              // });
            });
        } else {
          if (
            !this.formValidate.store_name ||
            !this.formValidate.cate_id ||
            !this.formValidate.keyword ||
            !this.formValidate.image ||
            !this.formValidate.slider_image
          ) {
            this.$message.warning("请填写完整商品信息！");
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-card__body {
  padding-right: 100px;
}
</style>
